# 一、创建一个名为Person的类，具有以下属性和方法：
#     属性：name（姓名），age（年龄）
#     方法：greet()，打印出一句问候语，包括该人的姓名和年龄
# class Person():
#     def __init__(self, name, age):
#          self.per_info={'姓名':name, '年龄': age}
#
#     def get_per_info(self):
#         return self.per_info
#
#     def greet(self):
#         print(f"你好,我叫{self.per_info['姓名']},我今年{self.per_info['年龄']}岁了")
# WuXia=Person('wuhanxia',24)
# print(WuXia.get_per_info())
# WuXia.greet()

#
# 二、定义一个"人"类
#     1.小明和小美都爱跑步
#     2.小美体重45.0公斤
#     3.小明体重75.0公斤
#     4.每次跑步都会减少0.5公斤
#     5.每次吃东西都会增加1公斤
# class Human:
#     def __init__(self, name, weight):
#         self.name = name
#         self.weight = weight
#
#     def run(self):
#         self.weight-=0.5
#         return f'{self.name}跑步后的体重是{self.weight}'
#
#     def eat(self):
#         self.weight += 1
#         return f'{self.name}吃饭后的体重是{self.weight}'
#
# xiaoming = Human('小明',75)
# xiaomei = Human('小美',45)
# print(xiaoming.eat())
# print(xiaoming.run())
#
# 三、定义一个学生Student类。有下面的实例属性：
#     1 姓名 name
#     2 年龄 age
#     3 成绩 score（语文，数学，英语) [每课成绩的类型为整数]
# 实例方法：
#     1 获取学生的姓名：get_name() 返回类型:str
#     2 获取学生的年龄：get_age() 返回类型:int
#     3 返回3门科目中最高的分数。get_max_score() 返回类型:int
#     4 将每个实例学生对象写进txt文件里，要持久保存
#     举例：{"姓名":"a","年龄":29,"成绩":{"语文":99,"数学":100,"英语":85}
#     5 获取所有学生的信息
#     写好类以后，可以定义2个同学测试下:
#     zm = Student('zhangming',20,[69,88,100])
# class Student:
#     def __init__(self, name, age, score):
#         self.name = name
#         self.age = age
#         self.score = score
#
#     def get_name(self) -> str:
#         return self.name
#
#     def get_age(self) -> int:
#         return self.age
#
#     def get_max_score(self) -> int:
#         return max(self.score)

    # {"姓名":"a","年龄":29,"成绩":{"语文":99,"数学":100,"英语":85}

#     def save_stu_info(self):
#         with open('./StudentInfo.txt', 'a', encoding='utf-8') as f:
#             info = {"姓名": self.name, "年龄": self.age,
#                     "成绩": {"语文": self.score[0], "数学": self.score[1], "英语": self.score[2]}}
#             json_str_info = json.dumps(info,ensure_ascii=False)  # 将info转换成json格式的字符串
#             f.write(json_str_info + '\n')
#
#     @staticmethod
#     def get_all_stu_info():  # 将实例方法转换成静态方法
#         with open('./StudentInfo.txt', 'r+', encoding='utf-8') as f:
#             return f.read()
# zm = Student('zhangming',20,[69,88,100])
# dz = Student('dengze',20,[69,88,100])
# xiaoyang = Student('xiaoyang',20,[69,88,100])
# # print(zm.get_name())
# # print(zm.get_max_score())
# # zm.save_stu_info()
# # dz.save_stu_info()
# # xiaoyang.save_stu_info()
# print(Student.get_all_stu_info())

# 四、做一个学生点名系统，系统里支持如下方法
#     存入学生（姓名、年龄、家庭地址、手机号）： 存入成功后，提示xxx存入成功
#     更改学生（姓名、年龄、家庭地址、手机号）：可以修改学生内容的任意一个
#     展示全部学生：可以看到全部的学生的信息
#     学生姓名：随机抽取任意一个存在的学生信息，然后打印：到！ 举例： 刘闯到！
import json, random

class StudentSystem:

    @classmethod
    def add_stu(cls, name, age, address, phone):
        data = {'姓名': name, '年龄': age, '家庭住址': address, '手机号': phone}
        with open('./Student.txt', 'a+', encoding='utf-8') as f:
            json_data = json.dumps(data, ensure_ascii=False)
            f.write(json_data + '\n')
            f.flush()
            print(f'{name}信息保存成功！')

    @classmethod
    def load_all_stu_info(cls):
        all_stu_info = []
        with open('./Student.txt', 'r', encoding='utf-8') as f:
            for i in f:
                stu = json.loads(i)
                all_stu_info.append(stu)
        return all_stu_info

    @classmethod
    def write_stu_info(cls, info):
        with open('./Student.txt', 'w', encoding='utf-8') as f:
            for i in info:
                json_stu_info = json.dumps(i, ensure_ascii=False)
                f.write(json_stu_info + '\n')

    @classmethod
    def update_stu(cls, name, key, value):
        """
        修改学生信息
        :param name: 学生姓名
        :param key:  要改的字段
        :param value: 修改过后的值
        :return: None
        """
        stu_info = cls.load_all_stu_info()  # 加载全部学生信息
        found = False  # 判断学生是否存在
        for i in stu_info:
            if i['姓名'] == name:
                i[key] = value
                found = True
                break
        if found:
            cls.write_stu_info(stu_info)  # 重新写入学生信息
            print(f'{name}信息修改成功')
        else:
            print(f'{name}在系统中不存在，请先添加！')

    @classmethod
    def delete_stu(cls, name):
        stu_info = cls.load_all_stu_info()  # 加载全部学生信息
        found = False
        delete_index = 99
        for i in range(len(stu_info)):
            if stu_info[i]['姓名'] == name:
                delete_index = i
                found = True
                break
        if found:
            stu_info.pop(delete_index)  # 在学生列表中删除目标学生信息
            cls.write_stu_info(stu_info)  # 重新写入学生信息
            print(f'{name}的信息删除成功！')
        else:
            print(f'{name}的信息不存在！')

    @classmethod
    def roll_stu(cls):
        stu_info = cls.load_all_stu_info()  # 加载全部学生信息
        stu_name = [i['姓名'] for i in stu_info]  # 将学生姓名提取出来
        roll_name = random.choice(stu_name)
        print(f'{roll_name}到！')

# StudentSystem.add_stu('dengze3',18,'辽宁沈阳','18541241540')
# StudentSystem.add_stu('dengze4',18,'辽宁沈阳','18541241540')
# StudentSystem.add_stu('dengze5',18,'辽宁沈阳','18541241540')
# StudentSystem.add_stu('dengze6',18,'辽宁沈阳','18541241540')
# StudentSystem.add_stu('dengze7',18,'辽宁沈阳','18541241540')
# StudentSystem.add_stu('dengze8',18,'辽宁沈阳','18541241540')
# StudentSystem.update_stu('dengze1','年龄',28)
# StudentSystem.update_stu('dengze3','年龄',28)
# StudentSystem.delete_stu('dengze1')
# print(StudentSystem.load_all_stu_info())
# StudentSystem.roll_stu()
#
# 五、点餐管理系统
#     1、餐馆可以新增菜品、下架菜品、修改菜品
#     2、每个菜品，都有对应的库存，所有菜品的库存均为999，每出一道菜，库存-1
#     菜品有对应的价格，餐厅老板定义价格每道菜不允许超过15元，没有小数单位，均为整数
#     3、餐馆后台有点赞系统，能够收集客户对菜品的喜好，0~5分
#     4、有菜品评分提报功能，对平均分数（菜品总分/打分人数）低于3分的菜品进行强制下架
import pymysql


import json


class OrderDishMangeSystem:
    # 菜名，库存，价格
    # 价格判断
    @classmethod
    def add_dish(cls, dish_name, price):
        if not isinstance(price, int):
            raise TypeError('您的价格输入有误！请输入小于15元的整数')
        if 0 < price <= 15:
            dish_info = {'菜品名称': dish_name, '库存': 999, '菜品价格': price, '点餐客户': []}
            with open('./DishMenu.txt', 'a+', encoding='utf-8') as f:
                f.write(json.dumps(dish_info, ensure_ascii=False) + '\n')  # 将菜品以json格式字符串存入菜单中
                return f'{dish_name}添加成功！'
        else:
            raise ValueError(f'请输入合理的价格，{dish_name}的价格超过了15元！')

    @classmethod
    def write_dishes_menu(cls, dishinfo):
        with open('./DishMenu.txt', 'w', encoding='utf-8') as f:
            for i in dishinfo:
                f.write(json.dumps(i, ensure_ascii=False) + '\n')

    @classmethod
    def load_dishes_menu(cls):
        dishes = []  # 用来保存所有菜品的信息
        with open('./DishMenu.txt', 'r', encoding='utf-8') as f:
            for i in f:
                dishes.append(json.loads(i))  # 逐行保存每个菜品信息
        return dishes

    @classmethod
    def delete_dish(cls, dish_name):
        dishes = cls.load_dishes_menu()
        delete_dish_index = 9999  # 初始化要下架菜品的索引号
        for i in range(len(dishes)):
            if dishes[i]['菜品名称'] == dish_name:
                delete_dish_index = i
                dishes.pop(delete_dish_index)  # 删除要下架的菜品信息
                cls.write_dishes_menu(dishes)
                return f'{dish_name}下架成功！'
        return f'{dish_name}没有在菜单中，不需要下架！'

    @classmethod
    def update_dish(cls, dish_name, newprice):
        if not isinstance(newprice, int) or newprice > 15:
            raise ValueError('您的价格输入有误，请输入小于等于15元的整数价格！')
        dishes = cls.load_dishes_menu()  # 加载菜单中全部菜品信息
        for i in dishes:
            if i['菜品名称'] == dish_name:
                i['菜品价格'] = newprice
                cls.write_dishes_menu(dishes)  # 将修改后的信息保存在菜单中
                return f'{dish_name}的价格修改成功！'
        return f'{dish_name}没有在菜单中，无法修改！'

    @classmethod
    def order_dish(cls, dish_name, amount, who):
        dishes = cls.load_dishes_menu()
        for i in dishes:
            if i['菜品名称'] == dish_name and i['库存'] >= amount:
                i['库存'] -= amount
                i['点餐客户'].append({'点餐人': who, '评价分数': None})
                cls.write_dishes_menu(dishes)
                return f'{dish_name}点餐成功！'
            elif i['菜品名称'] == dish_name and i['库存'] < amount:
                num = i['库存']
                return f'{dish_name}仅剩{num}盘，请减少点餐数量！'

        return f'你点的{dish_name}，在菜单中不存在！'

    @classmethod
    def dish_comment(cls, dish_name, score, who):
        dishes = cls.load_dishes_menu()  # 加载菜单
        for i in dishes:
            if i['菜品名称'] == dish_name:
                for j in i['点餐客户']:
                    if j['点餐人'] == who:
                        j['评价分数'] = max(0, min(score, 5))
                        cls.write_dishes_menu(dishes)
                        return '评分成功'
                return f'您没有点过{dish_name},不能评分！'
        return f'{dish_name}不在菜单中'

    @classmethod
    def inspection(cls):
        dishes = cls.load_dishes_menu()  # 加载菜单
        order_count = []
        sum_score = 0
        dish_names = []
        for i in dishes:
            if not i['点餐客户']:
                continue
            else:
                for j in i['点餐客户']:
                    if j['评价分数'] is None:
                        continue
                    sum_score += j['评价分数']
                    order_count.append(j)
                    avg_score = sum_score / len(order_count)
                    if avg_score < 3:
                        dish_names.append(i)
        for i in dish_names:
            cls.delete_dish(i['菜品名称'])

# print(OrderDishMangeSystem.add_dish('锅包肉', 15))
# print(OrderDishMangeSystem.delete_dish('糖醋排骨2'))
# print(OrderDishMangeSystem.order_dish('红烧排骨1', 10))
# print(OrderDishMangeSystem.order_dish('锅包肉', 10, '邓泽'))
# print(OrderDishMangeSystem.dish_comment('锅包肉', -5, '邓泽'))
# OrderDishMangeSystem.inspection()
